package zuochengyun;

import list.LinkedListCreate;
import list.LinkedListUtil;
import list.ListNode;

public class ListNumberAdd {

	public static void main(String[] args) {
		int[] array1 = { 4, 3, 9, 5 };
		int[] array2 = { 9, 6, 8, 1, 7 };
		ListNode head1 = LinkedListCreate.createList(array1);
		ListNode head2 = LinkedListCreate.createList(array2);
		ListNode sum = addList(head1, head2);
		LinkedListCreate.printList(sum);
	}

	public static ListNode addList(ListNode head1, ListNode head2) {
		if (head1 == null || head2 == null) {
			return head1 == null ? head2 : head1;
		}
		head1 = LinkedListUtil.reverse(head1);
		head2 = LinkedListUtil.reverse(head2);

		LinkedListCreate.printList(head1);
		LinkedListCreate.printList(head2);
		int carry = 0;
		int n1, n2;
		int res = 0;
		ListNode temp1 = head1, temp2 = head2;
		n1 = temp1.val;
		n2 = temp2.val;
		ListNode pre = new ListNode((n1 + n2 + carry) % 10);
		ListNode sumListHead = pre;
		carry = (n1 + n2 + carry) / 10;
		temp1 = temp1.next;
		temp2 = temp2.next;
		while (temp1 != null || temp2 != null) {
			n1 = temp1 == null ? 0 : temp1.val;
			n2 = temp2 == null ? 0 : temp2.val;
			res = (n1 + n2 + carry) % 10;
			ListNode sumListNode = new ListNode(res);
			System.out.println("res " + res + " carry :" + carry);
			pre.next = sumListNode;
			pre = sumListNode;
			carry = (n1 + n2 + carry) / 10;
			temp1 = temp1 == null ? null : temp1.next;
			temp2 = temp2 == null ? null : temp2.next;
		}
		if (carry != 0) {
			ListNode sumListNode = new ListNode(carry);
			pre.next = sumListNode;
		}
		head1 = LinkedListUtil.reverse(head1);
		head2 = LinkedListUtil.reverse(head2);
		return LinkedListUtil.reverse(sumListHead);
	}
}
